﻿using Bordspil.Models;
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Bordspil.Controllers
{
    public class HomeController : Controller
    {
        private IAppRepository m_repository = null;

        public HomeController()
        {
            m_repository = new AppRepository();
        }

        public HomeController(IAppRepository rep)
        {
            m_repository = rep;
        }

        public ActionResult Index()
        {
            //Sækir alla leiki sem eru virkir
            var activeGames = from games in m_repository.GetGames()
                              where games.IsActive == true
                              select games;

            return View( activeGames );
        }

        public JsonResult GetPopular()
        {
            //Sækir vinsælustu leikina
            var popularGames = (from games in m_repository.GetAllGames()
                                orderby games.Rating descending
                                select games);
        
            return Json(popularGames, JsonRequestBehavior.AllowGet); 
        }

        public JsonResult GetNewest()
        {
            //Sækir nýjustu leikina eftir Id
            var newestGames = (from games in m_repository.GetAllGames()
                                orderby games.Id descending
                                select games);
            
            return Json(newestGames, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetActiveGames(string theGame)
        {
            //Skilar öllum leikjum sem eru virkir og með færri leikmenn en hámarksfjöldi leyfir
            var activeGames = from games in m_repository.GetGames()
                               where games.IsActive == true 
                               && games.NumberOfPlayers < games.Games.MaxPlayers 
                               && games.Games.GameName == theGame
                               select games;

            return Json(activeGames, JsonRequestBehavior.AllowGet);
        }

       
        public JsonResult GetTheGameRating(string theGame)
        {
            //skilar ollum leikjum og haegt ad nota ur tessu medal annars Rating og mynd af leik ofl
            var result = from games in m_repository.GetAllGames()
                         where games.GameName == theGame
                         select games.Rating;

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult RateGame(string UserName, string Value, string theGame)
        {
            int gameId = 0;
            if (theGame == "TicTacToe")
            {
                gameId = 2;
            }
            else if (theGame == "Kindo")
            {
                gameId = 1;
            }
            else
            {
                return Json("Engin leikur valin", JsonRequestBehavior.AllowGet);
            }

            if (Value == null)
            {
                return Json("tomt", JsonRequestBehavior.AllowGet);
            }

            //Vel notandan sem mogulega hefur gefid leik einkun adur
            var hasRated = (from r in m_repository.GetAllGameRankings()
                            where r.UserName == UserName && r.GameId == gameId
                            select r).SingleOrDefault();

            //ef hann hefur gefid einkun aetti ad koma null og ta hefur notandi gefid einkun adur
            //og getur tad ekki aftur
            if (hasRated != null)
            {
                return Json("Buin", JsonRequestBehavior.AllowGet);
            }
            else
            {
                //annars verdur til nytt tilvik af GameRankin og tad sett i database
                GameRanking newGameRank = new GameRanking();
                newGameRank.GameId = gameId;
                newGameRank.UserName = UserName;
                if (Value == "+")
                {
                    newGameRank.Rating += 1;
                }
                else
                {
                    newGameRank.Rating -= 1;
                }

                m_repository.AddGameRating(newGameRank);
                m_repository.Save();
            }

            //vel leikinn sem notandi vill gefa einkun
            var result = (from games in m_repository.GetAllGames()
                          where games.Id == gameId
                          select games).SingleOrDefault();

            if (Value == "+")
            {
                result.Rating += 1;
            }
            else if (Value == "-")
            {
                result.Rating -= 1;
            }

            //vista database breytinganar
            m_repository.Save();

            return Json(Value, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetPlayersByInstanceId(int? instanceId)
        {
            //Skilar lista af öllum spilurum sem eru að spila ákveðið instance af leik
            var result = from r in m_repository.GetPlayerList()
                         where r.id == instanceId
                         select r;

            if (result == null)
            {
                return Json("Leikur finnst ekki", JsonRequestBehavior.AllowGet);
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }


        public ActionResult Chat()
        {
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            //kodi fengin fra stackoverflow, snorra og google utfaert fra teim sources
            if (ModelState.IsValid)
            {
                if (file == null)
                {
                    ModelState.AddModelError("File", "Vinsamlegast settu inn skrá");
                }
                else if (file.ContentLength > 0)
                {
                    int MaxContentLength = 1024 * 1024 * 3; //3 MB
                    string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };

                    if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                    {
                        ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                    }
                    else if (file.ContentLength > MaxContentLength)
                    {
                        ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                    }
                    else
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var path = Path.Combine(Server.MapPath("~/Images/UserImg"), fileName);
                        file.SaveAs(path);
                        ModelState.Clear();
                        ViewBag.Message = "File uploaded successfully";
                    }
                }
            }
            return View();
        }
    }
}
